package org.sardine.util;

import org.apache.log4j.Logger;

public class Wildcard {
	
	private static final Logger log = Logger.getLogger(Wildcard.class);
	
	public static boolean match(String text,String pattern){
		
		
		boolean result = false;
		
		String[] part = pattern.split("\\*");
		
		int beginIndex = 0;

		for(String s : part){
			log.debug("\""+s+"\"        begin index = "+beginIndex);
			
			int findIndex = text.indexOf(s,beginIndex);

			if(findIndex > -1){
				result = true;
				beginIndex = findIndex + s.length();
			}else{
				int qIndex = s.indexOf("?");
				
				if(qIndex > -1){
					int increment = text.length() - s.length();
					int limitIndex = beginIndex + increment;
					for(int j=beginIndex;j<limitIndex+1;j++){
						//textʣ���ַ���С��pattern�Ļ���ֱ��Ϊfalse��������ѭ��
						int surplusLength = text.length() - j;
						if(surplusLength < s.length()){
							result = false;
							break;
						}
						String word = text.substring(j, j + s.length());
						boolean m = like(word,s);
						if(m){
							beginIndex = j + s.length();
							result = true;
							break;
						}else{
							result = false;
						}
						/*��֤subString
						if((j - oldBeginIndex) == increment){
							break;
						}*/
					}
					
				}else{
					result = false;
					break;
				}
				
			}
			
		}
		log.debug("beginIndex = "+beginIndex);
		if(result && beginIndex < text.length() && !pattern.endsWith("*")){
			result = false;
		}
		
		log.debug("\""+text+"\" match \""+pattern+"\" is "+result);
		
		return result;
		
	}
	
	public static boolean like(String text,String pattern){
		
		boolean result = false;
		log.debug("    "+text+" , "+pattern);
		int tBeginIndex = 0;
		int patternLength = pattern.length();
		int textLength = text.length();
		for(int i=0;i<patternLength;i++){
			char c = pattern.charAt(i);
			//System.out.println(c+"   tBeginIndex = "+tBeginIndex);
			if(c == '?'){
				if(tBeginIndex == textLength){
					result = false;
					break;
				}
				int unknowChar = text.charAt(tBeginIndex);
				if(unknowChar > -1){
					result = true;
					tBeginIndex++;
				}else{
					result = false;
					break;
				}
				
			}else if(c == '*'){
				
			}else{
				char findChar = text.charAt(tBeginIndex);
				if(c == findChar){
					result = true;
					tBeginIndex++;
				}else{
					result = false;
					break;
				}
			}
		}
		
		
		//System.out.println(result);
		return result;
		
	}

}
